package com.codechuan.didi_web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.codechuan.didi_web.common.Constant;
import com.codechuan.didi_web.entity.SysUserAccount;
import com.codechuan.didi_web.entity.SysUserKey;
import com.codechuan.didi_web.entity.SysUserToken;
import com.codechuan.didi_web.mapper.SysUserAccountMapper;
import com.codechuan.didi_web.mapper.SysUserKeyMapper;
import com.codechuan.didi_web.mapper.SysUserTokenMapper;
import com.codechuan.didi_web.service.LoginControllerService;
import com.codechuan.didi_web.utils.ResultUtils;
import com.codechuan.didi_web.utils.SnowflakeIdGenerator;
import com.codechuan.didi_web.vo.ResultVO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Console;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class LoginControllerServiceImpl implements LoginControllerService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private SysUserAccountMapper sysUserAccountMapper;

    @Resource
    private SysUserTokenMapper sysUserTokenMapper;

    @Resource
    private SysUserKeyMapper sysUserKeyMapper;

    /**
     * @param keyNumber 卡密
     * @return 返回成功或失败的消息
     * @Deprecated 卡密登录
     */
    @Override
    public ResultVO<Object> login(String keyNumber, String token, String account) {
        // 校验卡密是否到期和绑定的用户
        SysUserKey sysUserKey = sysUserKeyMapper.selectByKey(keyNumber);
        if (sysUserKey == null)
            throw new RuntimeException("卡密不存在,或者卡密错误~");
        // 校验使用者和当前账号是否一样
        if (!sysUserKey.getAccount().equals(account) && !sysUserKey.getAccount().equals("未使用"))
            throw new RuntimeException("该卡密不归你使用哦~");
        // 校验卡密是否封停
        if (sysUserKey.getDelFlag().equals("1"))
            throw new RuntimeException("该卡密已被封停~");
        // 校验卡密是否到期
        if (sysUserKey.getExpirationTime() != null) {
            // 获取到期时间
            String expTime = Constant.format.format(sysUserKey.getExpirationTime());


            // 解析指定的日期时间字符串
            LocalDateTime specifiedDateTime = LocalDateTime.parse(expTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            // 获取当前日期时间
            LocalDateTime currentDateTime = LocalDateTime.now();

            // 比较当前时间是否大于指定时间
            boolean isCurrentDateTimeAfterSpecified = currentDateTime.isAfter(specifiedDateTime);

            // 输出结果
            if (isCurrentDateTimeAfterSpecified) {
                throw new RuntimeException("卡密已到期~");
            }
        }
        String keyNumber1 = sysUserKey.getKeyNumber();
        String keySubstring = keyNumber1.substring(0, 2);
        Calendar calendar = Calendar.getInstance();
        switch (keySubstring) {
            case "TK":
                // 获取到期时间
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                // 消息提示
                break;
            case "ZK":
                calendar.add(Calendar.DAY_OF_MONTH, 7);
                break;
            case "YK":
                calendar.add(Calendar.DAY_OF_MONTH, 30);

                break;
            case "CS":
                // 在当前时间基础上，增加5小时
                calendar.add(Calendar.HOUR_OF_DAY, 5);
                break;
        }
        // 设置卡密到期时间和激活时间
        sysUserKey.setExpirationTime(calendar.getTime());
        sysUserKey.setActivationTime(new Date());
        sysUserKey.setAccount(account);
        sysUserKey.setIsActivated("1");
        sysUserKeyMapper.updateByPrimaryKey(sysUserKey);
        // 通过account拿token去redis判断token在不在或者是不是一样的 不是一样的则被别人登录 不在则直接重新绑定
        SysUserAccount queryOn = sysUserAccountMapper.selectOneByAccount(account);
        if (queryOn != null && queryOn.getMyToken() != null) {
            // 查询redis中的token
            Boolean isNull = redisTemplate.hasKey(queryOn.getMyToken());
            if (token != null && !token.equals(queryOn.getMyToken())) {
                return ResultUtils.error(500, "该账户已被别的网页登录,请解绑", "该账户已被别的网页登录,请解绑");
            }
            if (Boolean.TRUE.equals(isNull)) {
                // 遍历小号列表修改所以小号状态为正常
                List<SysUserToken> sysUserTokens = sysUserTokenMapper.selectAllTokenByAccount(account);
                for (SysUserToken sysUserToken : sysUserTokens) {
                    if (sysUserToken.getTokenStatus().equals("正常")) {
                        continue;
                    }
                    sysUserToken.setTokenStatus("正常");
                    sysUserTokenMapper.updateByPrimaryKey(sysUserToken);
                }
                return ResultUtils.success(queryOn.getMyToken(), "登录成功");
            }
        }
        // UUID生成一个TOKEN
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1);
        uuid = uuid + idGenerator.nextId();
        // 封装value
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("keyNumber", account);
        redisTemplate.opsForValue().set(uuid, jsonObject.toString(), Duration.ofHours(24));
        // 先删除后新增
        sysUserAccountMapper.deleteByPrimaryKey(account);
        // 往账户表放一个token用来校验同一个网页二次登录不需要换token,失效的时候才换
        SysUserAccount sysUserAccount = new SysUserAccount(account);
        sysUserAccount.setMyToken(uuid);
        sysUserAccountMapper.insert(sysUserAccount);
        return ResultUtils.success(uuid, "登录成功");
    }
}